package com.bawei.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.home.databinding.ItemVideoLayoutBinding
import com.bawei.image.ImageLoadUtil
import com.bawei.image.ImageOptions
import com.bumptech.glide.Glide
import kotlin.math.max

/**
 * Author: Jason Zhang
 * Date: 2024/9/20
 * Desc: 首页视频列表适配器
 */
class HomeVideoListAdapter constructor(private val list: MutableList<SimpleVideoEntity>): RecyclerView.Adapter<HomeVideoListAdapter.ItemViewHolder>() {

    private var scrollState = RecyclerView.SCROLL_STATE_IDLE //滚动停止
    private var isPreloading = false //是否处于预加载中
    var preloadData: (() -> Unit)? = null //预加载执行方法
    var preloadEndCount = 0 //滑动到倒数第几个Item的时候触发预加载

    private var itemClickListener: OnItemClickListener? = null

    fun setOnItemClickListener(listener: OnItemClickListener){
        itemClickListener = listener
    }

    inner class ItemViewHolder(val dataBinding: ItemVideoLayoutBinding): RecyclerView.ViewHolder(dataBinding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val dataBinding = ItemVideoLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(dataBinding)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val entity = list[position]
        //设置标题和描述
        holder.dataBinding.tvTitle.text = entity.title
        holder.dataBinding.tvDesc.text = entity.description
        //作者头像
        ImageLoadUtil.with(holder.dataBinding.root.context)
            .setOptions(ImageOptions.Builder.isCircle(true).build())
            .loadUrl(entity.avatar_url)
            .into(holder.dataBinding.ivAvatar)
        //视频封面图
        ImageLoadUtil.with(holder.dataBinding.root.context)
            .setOptions(ImageOptions.Builder.isCircle(false).build())
            .loadUrl(entity.videomainimag)
            .into(holder.dataBinding.ivVideoThumbnail)
        //设置按钮点击事件
        holder.dataBinding.ivVideoPlay.setOnClickListener {
            itemClickListener?.onItemClick(it, position)
        }
        holder.dataBinding.ivCommend.setOnClickListener {
            itemClickListener?.onItemClick(it, position)
        }
        holder.dataBinding.ivMore.setOnClickListener {
            itemClickListener?.onItemClick(it, position)
        }

        //检查是否执行预加载逻辑
        checkPreload(position)
    }


    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }



    private fun checkPreload(position: Int){
        if (scrollState != RecyclerView.SCROLL_STATE_IDLE //滚动中预加载
            && position == max(list.size - 1 - preloadEndCount, 0) //确保Position不能为负数
            && !isPreloading){
            isPreloading = true
            //执行预加载的方法
            preloadData?.invoke()
        } else {
            isPreloading = false
        }
    }

    /**
     * 当ItemView被回收时，主动释放ImageView
     */
    override fun onViewRecycled(holder: ItemViewHolder) {
       Glide.with(holder.dataBinding.root.context).clear(holder.dataBinding.ivVideoThumbnail)
       Glide.with(holder.dataBinding.root.context).clear(holder.dataBinding.ivAvatar)
    }

    //获取Item的数量
    override fun getItemCount(): Int = list.size

    //获取Item唯一标识
    override fun getItemId(position: Int): Long = list[position].id.toLong()

    //如果页面是多布局的话，需要返回不同的值
    override fun getItemViewType(position: Int): Int {
        return 0
    }
    interface OnItemClickListener{
        fun onItemClick(v: View, position: Int)
    }

}
